package main

import (
	"net/http"
	"html/template"
)

type SearchRes struct {
	Anima []AnimaInfo
	Comic []ComicInfo
	Game []GameInfo
	Novel []NovelInfo
	Keyword string
	Categorys []string
}

func handleSearch(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method != http.MethodGet && r.Method != http.MethodPost {
		t, _ := template.ParseFiles("template/rawtext.gtpl")
		t.Execute(w, "Invalid http method.")
		return
	}

	var (
		res SearchRes
	)

	// Setup query condition.
	res.Keyword = r.PostForm.Get("keyword")
	cond_names_have := cond.Or("name__icontains", res.Keyword).
		Or("jp_name__icontains", res.Keyword).
		Or("oth_name__icontains", res.Keyword).
		Or("series__icontains", res.Keyword)

	// Get QuerySeter object, with table name.
	// Then query them.
	res.Categorys = r.PostForm["category"]
	for _, r_category := range res.Categorys {
		switch r_category {
		case "anima":
			qs := dborm.QueryTable("anima_info")
			qs.SetCond(cond_names_have).All(&res.Anima)
		case "comic":
			qs := dborm.QueryTable("comic_info")
			qs.SetCond(cond_names_have).All(&res.Comic)
		case "game":
			qs := dborm.QueryTable("game_info")
			qs.SetCond(cond_names_have).All(&res.Game)
		case "novel":
			qs := dborm.QueryTable("novel_info")
			qs.SetCond(cond_names_have).All(&res.Novel)
		}
	}

	t, _ := template.ParseFiles("template/search.gtpl")
	t.Execute(w, res)

	return
}

